﻿using Moven.Controls;
using Moven.Droid.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using System.ComponentModel;

[assembly:ExportRenderer(typeof(NativeCheckBox), typeof(NativeCheckBoxRenderer))]
namespace Moven.Droid.Renderers
{
	public class NativeCheckBoxRenderer: ViewRenderer<NativeCheckBox, Android.Widget.CheckBox>
	{
		bool _isDisposed;

		public NativeCheckBoxRenderer()
		{
			AutoPackage = false;
		}

		protected override void Dispose(bool disposing)
		{
			if (_isDisposed)
			{
				return;
			}
			if (Control != null)
			{
				Control.Click -= OnChecked;
			}
			this._isDisposed = true;
			base.Dispose(disposing);
		}

		protected override void OnElementChanged(ElementChangedEventArgs<NativeCheckBox> e)
		{
			base.OnElementChanged(e);
			if (e.OldElement == null && Control == null)
			{
				SetNativeCheckBox();
			}
			else
			{
				if (Control.Checked != Element.IsChecked)
				{
					var control = Control;
					control.Checked = Element.IsChecked;
					// Call JumpDrawablesToCurrentState to disable animation/transition
					// thanks to SO answer - http://stackoverflow.com/a/33021778
					// another answer http://stackoverflow.com/a/27139678 works too
					control.JumpDrawablesToCurrentState();
				}
			}
		}

		void SetNativeCheckBox()
		{
			var nativeControl = new Android.Widget.CheckBox(Context) { 
				Focusable = false, 
				Checked = Element.IsChecked};
			nativeControl.SetWidth(Element.WidthRequest.DpToPx());
			nativeControl.SetHeight(Element.HeightRequest.DpToPx());
			nativeControl.Click += OnChecked;
			SetNativeControl(nativeControl);
		}

		void OnChecked(object sender, object args)
		{
			Element.ToggleCommand?.Execute(null);
		}

		protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			base.OnElementPropertyChanged(sender, e);

			if (e.PropertyName == nameof(Element.IsChecked) && Control.Checked != Element.IsChecked)
			{
				Control.Checked = Element.IsChecked;
				Control.JumpDrawablesToCurrentState();
			}
		}
	}
}
